package com.r2coding.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务配置
 *
 * @author:98k灬
 * @since:2022/04/08 22:06
 **/
@Configuration
@EnableAuthorizationServer // 开启认证服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserDetailsService customerUserDetailService;

    @Resource
    TokenStore tokenStore;

    @Autowired
    DataSource dataSource;

    @Resource
    JwtAccessTokenConverter jwtAccessTokenConverter;

    @Resource
    TokenEnhancer jwtTokenEnhancer;

    @Bean
    public ClientDetailsService jdbcClientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    // 配置被允许访问此认证服务器的客户端信息
    // 1、内存方式  2、数据库方式
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 1、内存方式
        /*clients.inMemory()
                .withClient("98k") // 客户端ID
                .secret(passwordEncoder.encode("hk123456")) // 需要加密 客户端的密码
                .resourceIds("system-server") // 资源ID 针对的是微服务的名称
                .authorizedGrantTypes("authorization_code", "password", "refresh_token")
                .scopes("all")
                .autoApprove(false) // false:需要手动授权 true:不需要手动授权
                .redirectUris("http://www.baidu.com/");// 客户端回调地址*/
        // 2、JDBC方式
        clients.withClientDetails(jdbcClientDetailsService());
    }

    // 认证服务器的端点配置
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager); // 密码模式时需要这个authenticationManager实例
        endpoints.userDetailsService(customerUserDetailService); // 刷新令牌时需要使用
        endpoints.tokenStore(tokenStore).accessTokenConverter(jwtAccessTokenConverter);// 令牌的管理方式
        // 增强器
        TokenEnhancerChain chain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        chain.setTokenEnhancers(enhancerList);
        endpoints.tokenEnhancer(chain).accessTokenConverter(jwtAccessTokenConverter);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 认证后可访问 /oauth/check_token 默认拒绝访问
        security.checkTokenAccess("isAuthenticated()");
        // 所有人可访问/oauth/token_key 后面要获取公钥 默认拒绝访问
        security.tokenKeyAccess("permitAll()");
    }
}
